import 'dva/fetch';

export default (url, request) => {
  const { body: data = null } = request;

  const headers = new Headers();
  let body = null;

  if (data !== null) {
    if (data instanceof String) {
      headers.append('Content-Type', 'application/x-www-form-urlencoded');
      body = data;
    } else {
      let flag = false;
      const formData = new FormData();
      for (const key of Object.getOwnPropertyNames(data)) {
        const value = data[key];
        formData.append(key, value);
        if (value instanceof File) {
          flag = true;
          break;
        } else if (body === null) {
          body = `${key}=${value}`;
        } else {
          body += `&${key}=${value}`;
        }
      }
      if (flag) {
        body = formData;
      } else {
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
      }
    }
  }

  const req = new Request(url, {
    ...request, headers, body, credentials: 'same-origin',
  });

  return fetch(req);
};
